#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
# @Time    : 2022/08/26 15:29
# @Author  : elegantfrog
# @FileName: utils.py
import os
import base64
import json
from io import BytesIO


class aUtils():
    # 获取设备的SN码
    def getDevCode(self, path, type='r'):
        try:
            with open(path, type) as f:
                cpuinfo = f.readlines()
                res = cpuinfo[-1].split(':')[1].lstrip().replace('\n', '')
                return res
        except Exception as e:
            print(e)
            return None

    # 执行命令行
    def operateCommand(self, data):
        try:
            if data:
                print(data)
                res = os.popen(data['params'])
                print(res.readlines())
                return 'success'
            else:
                return None
        except Exception as e:
            print(e)
            return None

    # 设置设备参数（模组开关、蜂鸣器开关、补光灯）
    def setDevParams(self, path, params, fileJson):
        try:
            with open(path, 'w+') as f:
                f.write(params)
            res = self.getDevParams(fileJson)
            return {'status': 'success', 'data': res['data']}
        except Exception as e:
            print(e)
            return None

    # 获取设备参数（模组状态、蜂鸣器状态、补光灯、电流、电压）
    def getDevParams(self, fileJson):
        params = result = {
            'light': '',
            'brightness': '',
            'images': '',
            'volt': '',
            'cur': '',
            'alarm': '',
            'temp': ''
        }
        fileTime = 0
        try:
            for i in params.keys():
                if i == 'images':
                    self.operateCommand({'params': 'message_tools CatchOnePic'})
                    fileTime = int(os.path.getmtime(fileJson[i]))
                    with open(fileJson[i], 'rb') as f:
                        img = f.read()
                        base64_bytes = base64.b64encode(img)
                        base64_str = base64_bytes.decode("utf-8")
                    result[i] = base64_str
                else:
                    with open(fileJson[i], 'r') as f:
                        result[i] = f.readline().replace('\n', '')
            result['time'] = fileTime
            return {"status": 1, 'data': result}
        except Exception as e:
            print(e)
            return {"status": 0, 'data': []}

    # 更新配置文件
    def updateConfig(self, path, config, data):
        try:
            config[data['key']] = data['value']
            with open(path, 'w', encoding='utf-8') as fw:
                json.dump(config, fw)
            return 'success'
        except Exception as e:
            print(e)
            return None


if __name__ == '__main__':
    res = aUtils().getDevParams(123)
    print(res)
